import getDataDB from '@/api/agreeContractManagement.js'
import pageInitiate from './pageInitiate'
import currentPageConfig from './currentPageConfig'



/**
 * 装载form表单
 * @param {*} publicDetailData
 * @param {*} otherDetailData
 */
const mergeForm = (publicDetailData,otherDetailData,pageParam,pageSelf)=>{
  console.log('装载form表单 ==== 0 =========>',publicDetailData,otherDetailData,pageParam);
  const tempPI = pageInitiate(pageSelf)
  // 页面发起配置
  const tempConfig = tempPI[pageParam.actionCode]
  if(pageParam.status == 'c0'){
    // 流程发起
    console.log('装载form表单 流程发起 =============>',tempConfig);
  }


  if(otherDetailData){

  }else{
    // 只有公共详情

  }
}

const getOtherDetailIndo1 =async (pageSelf)=>{
  const actionCodeList = {
   // 合同中止详情
   '500001':()=>{
     return {
       urlName:'合同中止详情',
       param:{agreeId:pageSelf.bizId_},
       processEvent:(dbData)=>{

       }
     }
   },
   // 解除中止
   '500003':()=>{
     return {
       urlName:'合同中止详情',
       param:{agreeId:pageSelf.bizId_},
       processEvent:(dbData)=>{

       }
     }
   },
   // 用户申诉
   '500002':()=>{
     return {
       urlName:'合同中止详情',
       param:{agreeId:pageSelf.bizId_},
       processEvent:(dbData)=>{

       }
     }
   },
   // 合同终止
   '500002':()=>{
     return {
       urlName:'合同终止详情',
       param:{id:pageSelf.flowNo},
       processEvent:(dbData)=>{
         // window['globalData']['waitAgreeId'] = dbData.waitAgreeId
       }
     }
   },
  }
 const tempRes = null
 const temp = actionCodeList[pageSelf.flowCode_] && actionCodeList[pageSelf.flowCode_]()
 console.log('业务详情接口========= 0 ===========》',temp,pageSelf.flowCode_,pageSelf.PageParam);
 if(temp){
   const res = await getDataDB(temp.urlName,temp.param)
   if(res.success==true){
     temp.processEvent(res.result )

   }
   console.log('业务详情接口========= 1 ===========》',res);
 }
 return tempRes
}


//     {
//         "groupCode":"202120000",
//         "dataList":{
//           "合同信息":[
//             {"enName":"signName","cnName":"企业名称","type":"label","value":"中雄（荆州）信息公司北京分公司","numRowsOccupied":1,"numColumnOccupied":1,"formItemAttr":{},"itemAttr":{}},
//             {"enName":"agreeName","cnName":"合同名称","type":"label","value":"业务合作协议B端线上枣阳园区","numRowsOccupied":1,"numColumnOccupied":1,"formItemAttr":{},"itemAttr":{}},
//             {"enName":"agreeNo","cnName":"合同编号","type":"label","value":"DOC_02_1002202311161622520009","numRowsOccupied":1,"numColumnOccupied":1,"formItemAttr":{},"itemAttr":{}},
//             {"enName":"agreeCategory","cnName":"业务类型","type":"label","value":"灵工业务","numRowsOccupied":1,"numColumnOccupied":1,"formItemAttr":{},"itemAttr":{}},
//             {"enName":"agreeEnableTime|agreeExpireTime","cnName":"合同有限期","type":"label","value":"2023-11-16~2024-11-16","numRowsOccupied":1,"numColumnOccupied":1,"formItemAttr":{},"itemAttr":{}},
//             {"enName":"modelName","cnName":"合同模板","type":"label","value":"业务合作协议B端线上枣阳园区","numRowsOccupied":1,"numColumnOccupied":1,"formItemAttr":{},"itemAttr":{}}
//           ]
//         }
//       },

const tttttt = [
  {
      "groupName": "2023年11月30日",
      "dataList": [
          {
              "groupName": "合同中止",
              "dataList": [
                  {
                      "nameEn": "中止原因",
                      "value": "合同中止\n企业名称\n中雄（荆州）信息公司北京分公司\n合同名称\n业务合作协议 签订版本 B端线上\n合同编号\nDOC_02202311161628520012\n业务类型\n灵工业务\n合同有限期\n2023-11-16~2023-11-30\n中止原因\n请填写终止原因\n风控证明文件\n请上传文件",
                      "type": "label"
                  },
                  {
                      "nameEn": "风控证明文件",
                      "value": {
                          "id": 16286,
                          "url": "https://zxcloud-test.oss-cn-hangzhou.aliyuncs.com/user/contract/1701337939485_%E8%A1%A5%E5%85%85%E5%8D%8F%E8%AE%AE.pdf",
                          "fileName": "补充协议.pdf",
                      },
                      "type": "file"
                  },
                  {
                      "nameEn": "法务通知函",
                      "value": {
                          "id": 16286,
                          "url": "https://zxcloud-test.oss-cn-hangzhou.aliyuncs.com/user/contract/1701337939485_%E8%A1%A5%E5%85%85%E5%8D%8F%E8%AE%AE.pdf",
                          "fileName": "补充协议.pdf",
                      },
                      "type": "file"
                  }
              ]
          },
          {
              "groupName": "用户申诉",
              "dataList": [
                  {
                      "nameEn": "申诉说明",
                      "value": "申诉说明\n",
                      "type": "label"
                  },
                  {
                      "nameEn": "申诉文件",
                      "value": {
                          "id": 16308,
                          "url": "https://zxcloud-test.oss-cn-hangzhou.aliyuncs.com/user/contract/1701756755681_%E7%94%B3%E8%AF%89%E4%B8%AD%E6%AD%A2%E6%96%87%E4%BB%B6.pdf",
                          "fileName": "申诉中止文件.pdf",
                      },
                      "type": "file"
                  }
              ]
          },
          {
              "groupName": "解除终止",
              "dataList": [
                  {
                      "nameEn": "解除原因",
                      "value": "解除原因\n",
                      "type": "label"
                  }
              ]
          }
      ]
  }
]



const getOtherDetailInfo4AgreeId = async (pageSelf,PageParam)=>{
  const param = {agreeId:''}
  if(PageParam.status=='c0'){
    param.agreeId = PageParam.bizId
  }else{
    param.agreeId = PageParam.agreeId
  }
  console.log('根据合同id查询详情===============>',param,PageParam);
  const res = await getDataDB('根据合同id查询详情',param)
  if(res.success==false){
    pageSelf.$message.warning(res.message);
    return []
  }
  return res.result || []
}


/**
 * 获取当前页面参数
 * @param {*} pageSelf
 * @returns
 */
const getPageParam =async (pageSelf)=>{
  const pageParam = {
    status:'',
    bizId:'',
    flowCode:'',
    actionCode:'',
    flowNo:'',
    agreeId:''
  }
  // 只传合同id的合同详情
  if(pageSelf.$route.query.agreeId || pageSelf.agreeId){
    pageParam.status = 'd0'
    pageParam.agreeId = pageSelf.$route.query.agreeId || pageSelf.agreeId
    pageParam.actionCode = 'CM007'
    pageParam.bizId = ''
    pageParam.flowCode = ''
    pageParam.flowNo = ''
  }
  // 合同详情
  if(pageSelf.$route.query.actionCode && pageSelf.$route.query.bizId && pageSelf.$route.query.status){
    pageParam.status = pageSelf.$route.query.status
    pageParam.bizId = pageSelf.$route.query.bizId
    pageParam.actionCode = pageSelf.$route.query.actionCode
    pageParam.agreeId = pageSelf.$route.query.agreeId
    pageParam.flowNo = ''
    pageParam.flowCode = ''
  }
  if(pageSelf.actionCode && pageSelf.bizId && pageSelf.status){
    pageParam.status = pageSelf.status
    pageParam.bizId = pageSelf.bizId
    pageParam.actionCode = pageSelf.actionCode
    pageParam.agreeId = pageSelf.agreeId
    pageParam.flowNo = ''
    pageParam.flowCode = ''
  }
  if(pageSelf.$route.query.actionCode && pageSelf.$route.query.flowCode && pageSelf.$route.query.bizId && pageSelf.$route.query.status){
    pageParam.status = pageSelf.$route.query.status
    pageParam.bizId = pageSelf.$route.query.bizId
    pageParam.flowCode = pageSelf.$route.query.flowCode
    pageParam.actionCode = pageSelf.$route.query.actionCode
    pageParam.agreeId = ''
    pageParam.flowNo = ''
  }
 if(pageSelf.actionCode && pageSelf.flowCode&& pageSelf.flowNo && pageSelf.bizId  && pageSelf.status){
    const  temp =  pageSelf.ContractConfig('btnCode')
    const  temp1 =  pageSelf.ContractConfig('btnCode1')
    console.log('查询流程进度 ==0==>',{flowCode:pageSelf.flowCode,flowNo:pageSelf.flowNo});
    const res = await getDataDB('查询流程进度',{flowCode:pageSelf.flowCode,flowNo:pageSelf.flowNo})
    const nodeInfo = pageSelf.ContractConfig('','getWorkProgressData',res)//this.getWorkProgressData(res)
    console.log('查询流程进度 ==1==>',res,nodeInfo);
    pageParam.status =    nodeInfo.currentStatusConfigNode //flowCodeAction[pageSelf.flowCode] && flowCodeAction[pageSelf.flowCode](pageSelf.status,res) || 'c0' // sh
    pageParam.bizId =      pageSelf.bizId
    pageParam.flowCode =   pageSelf.flowCode
    pageParam.actionCode = temp1[pageSelf.actionCode]
    pageParam.flowNo =   pageSelf.flowNo
    pageParam.agreeId = pageSelf.agreeId
  }
  // // 合同审核详情
  // if(pageParam.actionCode=='CM000'){
  //   pageParam.status = 'c00'
  // }



 return pageParam
}

/**
 * 查询合同公共详情
 * @param {*} param
 * @param {*} type 1 审核的本协议 2 原协议
 */
const getData4ContractDetailsInfo = async (pageSelf,param,type='1')=>{
  let urlName = '查询合同详情(审核)'
  const param_ = {
    id:param.flowNo ,
    type, // 	1审核的本协议 2原协议
  }
  if(param.status=='c0'){
    // 发起详情
    urlName = '查询合同详情(发起)'
    param_.id = param.bizId
  }
  if(param.status=='d0'){
    // 发起详情
    urlName = '查询合同详情(发起)'
    param_.id = param.bizId || param.agreeId
  }
  console.log('检查接口参数==1====》',param,param_,urlName);
  const res = await getDataDB(urlName,param_)
  if(res.success==false){
    pageSelf.$message.warning(res.message);
    return null
  }
  return res.result
}

/**
 * 获取公共详情数据
 * @param {*} dataList 接口数据
 * @returns
 */
const getPublicDataList = (dataList) =>{
  const publicDataList = [
    { enName:'signName', cnName:'名称', type:'label',value:'--',numRowsOccupied: 1, numColumnOccupied: 1 ,formItemAttr:{},itemAttr:{}},
    { enName:'agreeName', cnName:'合同名称', type:'label',value:'--',numRowsOccupied: 1, numColumnOccupied: 1 ,formItemAttr:{},itemAttr:{}},
    { enName:'agreeNo', cnName:'合同编号', type:'label',value:'--',numRowsOccupied: 1, numColumnOccupied: 1 ,formItemAttr:{},itemAttr:{}},
    // 1：灵工业务，2：委托代征，3：灵工+委托代征（默认1
    { enName:'agreeCategory', cnName:'业务类型', type:'label',value:'--',numRowsOccupied: 1, numColumnOccupied: 1 ,formItemAttr:{},itemAttr:{}},
    // labelCol:{span: 2},wrapperCol:{span: 20}
    { enName:'agreeEnableTime|agreeExpireTime', cnName:'合同有限期', type:'label',value:'--',numRowsOccupied: 1, numColumnOccupied: 1 ,formItemAttr:{},itemAttr:{}},
    { enName:'modelName', cnName:'合同模板', type:'label',value:'--',numRowsOccupied: 1, numColumnOccupied: 1 ,formItemAttr:{},itemAttr:{}},
  ]
  const agreeCategoryList = {
    1:'灵工业务',2:'委托代征',3:'灵工+委托代征'
  }
  function addOneDay(dateStr) {
    // 创建一个新的 Date 对象，避免直接修改原日期对象
    let newDate = new Date(dateStr);
    // 获取当前日期的天数并加一
    const day_ = newDate.getDate();
   let date = new Date(newDate.setDate(day_ + 1));
   var year = date.getYear() + 1900; // getYear返回的是从1900年开始算起的年份，需加上1900
   var month = date.getMonth() + 1; // getMonth返回的是0-11，需要加1
   var day = date.getDate();

   // 格式化为yyyy-mm-dd格式
   var formattedDate = year + '-' + (month < 10 ? '0' + month : month) + '-' + (day < 10 ? '0' + day : day);
   return formattedDate;
 }
  const convEnNameList = {
    agreeCategory:(enName,dataList)=>{
      return agreeCategoryList[dataList[enName]]
    },
    'agreeEnableTime|agreeExpireTime':(enName,dataList,type)=>{
      const tempVals = []
      enName.split('|').forEach(n=>{
        dataList[n] && tempVals.push(dataList[n])
      })
      if(type=='1'){
        window['globalData']['agreeDateRangeNew'] = [tempVals[0],addOneDay(tempVals[1])]
      }
      if(type=='2'){
        window['globalData']['agreeDateRangeOld'] = [tempVals[0],addOneDay(tempVals[1])]
      }
      return tempVals.length>0&&tempVals.join('~') || null
    },
  }
  if(dataList){
    publicDataList.forEach(item=>{
      const {enName} = item
      const val_ = convEnNameList[enName] && convEnNameList[enName](enName,dataList) || dataList[enName]
      item.value = val_
    })
  }

  return publicDataList
}

/**
 * 获取公共详情数据
 * @param {*} pageSelf
 * @param {*} tabName
 * @returns
 */
const getPublicDetailInfo =async (pageSelf,tabName) =>{
  let type = '1' // 	1审核的本协议 2原协议
  if(tabName.indexOf('原协议')>=0){
    type = '2'
  }
  const dataList_p = await getData4ContractDetailsInfo(pageSelf,pageSelf.PageParam,type)
  const res = getPublicDataList(dataList_p)
  console.log('合同公共详情======= 0 =========》',tabName,res,dataList_p);
  // window['globalData']['signInfo'] = {signId:dataList_p['signId'],signName:dataList_p['signName'],signType:dataList_p['signType']}
  // window['globalData']['modelId'] = dataList_p['modelId']
  // window['globalData']['agreeCategory'] = dataList_p['agreeCategory']
  // 设置合同 状态 status
  pageSelf.agreeStatus = dataList_p['status']
  pageSelf.ReissueSigningConfig.agreeId= dataList_p['id']+''
  pageSelf.ReissueSigningConfig.flowCode= dataList_p['flowCode']+''
  return {form:res,ppsConfigUrl:dataList_p['agreeUrl']||''}
}




/**
 * 获取当前页面需要的配置数据
 * @param {*} pageSelf
 * @returns
 */
const createCurrentPageConfig = (pageSelf,param)=>{
  const temp = currentPageConfig()
  console.log('createCurrentPageConfig=========== 0 ==========>',temp,pageSelf,param);
  const res = temp[param.actionCode][param.status]
  pageSelf.currentPageConfig= res
  console.log('createCurrentPageConfig=========== 1 ==========>',res);
  return res
}

const createPageConfig =async (pageSelf,cpcItem,publicDetailData,dataSize,param,dataIndex)=>{
  const res= {}
  const {form,ppsConfigUrl} = publicDetailData
  const {configName,tabName} = cpcItem

  const otherDataArr =await getOtherDetailInfo4AgreeId(pageSelf,param)

  const tempPI = pageInitiate(pageSelf)
  // 页面发起配置
  const tempConfig = tempPI[param.actionCode]
  const {pageTitle,formRules,formDataList,btnList} = tempConfig
  pageSelf.pageTitle = pageTitle
  const getDataForOtherData = (otherDataArr_,publicDetailData_)=>{
    const getDataList = (dataList_)=>{
      const upLoadConfig = ()=>{
        return {
          // 此参数必填  上传路径
          dir: "/user/contract/",
          // 身份证  all   ；  单文件 对应 card1 ；   多文件 对应  card3 ； 身份证  对应  card1（身份证正面）、card2（身份证反面）
          model: "单文件",
          // 此参数选填   此属性只在 model= 身份证 时 启用   默认值文false
          showBG: false,
          // 此参数选填  表示是否可编辑
          readonly: false,
          // 提示信息
          tips:{
            card1: '请上传文件',
            card2: '这是提示信息',
            card3: '这是提示信息',
          },
          // 此参数选填   文件上传必填校验 默认为false 不校验   当值为true时进行强制校验  需要配合【getDataCheckRes】方法使用；
          // 方法【getDataCheckRes】的具体用法如: this.$refs.UpLoadFile.getDataCheckRes({ card1: "请上传身份证正面",card2: "请上传身份证反面", card3: "请上传附件"});
          // 其中 【getDataCheckRes】的参数辨识检验不通过时对应的提示信息；card1、card2、card3均可缺省，也可选填对应的字段    此参数可空
          required: true,
          // 此参数选填   要回显的数据 card1 card2 的值的格式为：{name:'',url:''} ;  card3 的值的格式为 [{name:'',url:''}，{name:'',url:''}]
          defaultFileList: {
            card1: {},
            card2: {},
            card3: [],
          },
          // 此参数集必填
          fielConfig: {
            // 允许上传的文件类型 当为空时表示不限制  默认为空
            //    可供选择类型：
            //          图片('jpg', 'png', 'jpeg')
            //          文档('xlsx', 'xls', 'pptx', 'ppt', 'pdf', 'doc', 'docx', 'txt')
            //          压缩包('zip', 'rar')  发票('pdf', 'jpg', 'png', 'jpeg', 'doc', 'docx', 'zip', 'rar')
            //          PDF(pdf)
            //          委托代征协议('pdf','jpg', 'png', 'jpeg')
            //          我的任务('jpg', 'png', 'jpeg','pdf','xlsx', 'xls', 'pdf', 'doc', 'docx','zip', 'rar' )
            // eg:
            //    当值为string类型时，对所有（card1,card2,card3）的有效；
            //    当值为对象（{"card1":'图片',"card2":'文档', "card3":'PDF'}）时，可指定每个（card1/card2/card3）所对应的类型
            type: "合同专用",
            // 允许上传的文件个数  默认值为1
            // eg: 1 表示只允许上传1个文件；
            //      当值为对象（{"card1":1,"card2":2, "card3":3}）时，可指定每个（card1/card2/card3）所对应的类型
            size: 1,
            // 上传的单个文件大小 单位为 MB  默认值为1
            //  eg: 当值为 number 时，对所有（card1,card2,card3）的有效；
            //        当值为对象（{"pdf":5,"xlsx":10, "zip":100}）时,可指定对应的文件类型的大小（单位：MB）
            singleFileSize: 100,
          },
        }
      }

      const extendedFileVerification=[{ 'groupName':'合同专用', suffixArr:['jpg','jpeg','png','pdf','doc','docx','xls','xlsx','zip','rar'],errorMsg:'只允许上传 jpg,jpeg,png,pdf,doc,docx,xls,xlsx,zip,rar类型文件' }]

      const typeAction = {
        'label':(nameEn,value,type)=>{
          return { enName:nameEn, cnName:nameEn, type:'label',value:value,numRowsOccupied: 2, numColumnOccupied: 2 ,formItemAttr:{labelCol:{span: 2},wrapperCol:{span: 20}},itemAttr:{}}
        },
        'file':(nameEn,value,type)=>{
          return { enName:nameEn, cnName:nameEn, type:'imgGroup',value:[{url:value.url,name:value.fileName}],numRowsOccupied: 1, numColumnOccupied: 2 ,formItemAttr:{labelCol:{span: 2},wrapperCol:{span: 20}},itemAttr:{config:upLoadConfig(),customRequestEvent:pageSelf.PUpLoadFileCustomRequestEvent,extendedFileVerification:extendedFileVerification }}
        }
      }
      const resObj = {}
      dataList_.forEach(item=>{
        const {groupName,dataList} = item
        const tempArr = []
        dataList.forEach(forItem=>{
          const {nameEn,value,type} = forItem
          typeAction[type] && tempArr.push(typeAction[type](nameEn,value,type))
        })

        resObj[groupName] = tempArr
      })
     return resObj
    }
    const resArr = []
    otherDataArr_.forEach(item=>{
      const {groupName,dataList} = item
      // 每一轮都带上相同的合同信息
      resArr.push({groupCode:groupName,dataList:{'合同信息':publicDetailData_,...getDataList(dataList)}})
    })
    return resArr
  }
  const tempObj = {
    ppsConfig:{
      model:'page',
      config:{title:'',visible: false, loading: false, width: '50vw',height: '60vh' },
      url:ppsConfigUrl
    },
    groupConfig:{
      show:true,
      dataSize:dataSize,
      collapseActionKey:'1'
    },
    formLayout:{ rowNum: 4, columnNum: 2, rowGap: "0px", rowHeight:'50px', coliumnGap: "0px", labelCol: { span: 4 }, wrapperCol: { span: 14 }, },
    formRules:formRules,
    formDataList:[],
    btnList:[]
  }
  const tempOtherData = getDataForOtherData(otherDataArr,form)
  if(param.status == 'c0'){
    // 流程发起
    console.log('装载form表单 流程发起 =============>',tempConfig);
    tempObj.btnList = btnList
    if(tempOtherData.length>0){
      tempObj.formDataList = [
        ...tempOtherData,
        {
          groupCode:tabName,
          dataList:{
            '合同信息':[...form],
            ...formDataList
          }
        }
      ]
      tempObj.groupConfig.dataSize = tempObj.formDataList.length
      tempObj.groupConfig.collapseActionKey = tempObj.formDataList.length
    }else{
      tempObj.formDataList = [
        {
          groupCode:tabName,
          dataList:{
            '合同信息':[...form],
            ...formDataList
          }
        }
      ]
    }
  }else{
    if(tempOtherData.length>0){
      tempObj.formDataList = tempOtherData
      tempObj.groupConfig.dataSize = tempObj.formDataList.length
      tempObj.groupConfig.collapseActionKey = tempObj.formDataList.length
    }else{
      tempObj.formDataList = [
        {
          groupCode:'',
          dataList:{
            '合同信息':[...form]
          }
        }
      ]
    }
  }
  res[configName] =tempObj
  console.log('form====================>',res,param,otherDataArr,tempOtherData);
  pageSelf.pageConfigList = {...pageSelf.pageConfigList,...res}

}






const pageInit = (pageSelf,...args)=>{
  getPageParam(pageSelf).then(async param=>{
    console.log('页面初始化数据 1====》',param,pageSelf);
    pageSelf.PageParam = param
    pageSelf.bizId_ = param.bizId
    pageSelf.flowCode_ = param.flowCode
    // 查询 当前业务对应的详情数据
    const currentPageConfig_ = createCurrentPageConfig(pageSelf,param)
    const dataSize = currentPageConfig_.length
    pageSelf.pageConfigList = {}
    currentPageConfig_.forEach(async (item,dataIndex)=>{
      const {tabName} = item
      const publicDetailData =await getPublicDetailInfo(pageSelf,tabName)
      console.log('合同公共详情======= 1 =========》',tabName,publicDetailData);
      createPageConfig(pageSelf,item,publicDetailData,dataSize,param,dataIndex)

      if(dataSize-1 ==dataIndex ){
        pageSelf.pageLoading = false
      }
    })
    // pageSelf.$nextTick(()=>{
    //   pageSelf.currentPageConfig= currentPageConfig_
    // })

  })
}

export default pageInit
